package com.zhoug.plugin.android.constgenerator.actions;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.search.FilenameIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.zhoug.plugin.android.constgenerator.ClassWriter;
import com.zhoug.plugin.android.constgenerator.beans.ConstField;
import com.zhoug.plugin.android.constgenerator.dialog.FieldTableDialog;
import com.zhoug.plugin.android.constgenerator.dialog.JsonDialog;
import com.zhoug.plugin.android.constgenerator.utils.ToastUtils;

import javax.swing.table.DefaultTableModel;
import java.util.ArrayList;
import java.util.List;

public class StartAction extends AnAction {
    private static final String TAG = "FindViewsAction";
    private List<ConstField> mConstFields = new ArrayList<>();
    private DefaultTableModel tableModel;

    //编辑器
    private Editor editor;
    //事件发生所在的文件
    private PsiFile psiFile;
    //项目
    private Project project;
    //Module
    private Module module;

    private FieldTableDialog fieldTableDialog;
    private ClassWriter classWriter;
    private JsonDialog jsonDialog;
    private AnActionEvent anActionEvent;

    @Override
    public void update(AnActionEvent anActionEvent) {
        Editor editor = anActionEvent.getData(PlatformDataKeys.EDITOR);
        if (editor != null) {
//            e.getPresentation().setEnabled(true);
            PsiFile psiFile = anActionEvent.getData(PlatformDataKeys.PSI_FILE);
            if (psiFile != null && (psiFile.getName().endsWith(".java") || psiFile.getName().endsWith(".kt"))) {
                anActionEvent.getPresentation().setVisible(true);
            } else {
                System.out.println("非java文件不显示插件按钮");
                anActionEvent.getPresentation().setVisible(false);
            }
        } else {
//            e.getPresentation().setEnabled(false);//回收,不可点击
            anActionEvent.getPresentation().setVisible(false);
        }

    }


    @Override
    public void actionPerformed(AnActionEvent anActionEvent) {
        editor = anActionEvent.getData(PlatformDataKeys.EDITOR);
        psiFile = anActionEvent.getData(PlatformDataKeys.PSI_FILE);
        project = anActionEvent.getData(PlatformDataKeys.PROJECT);
        module = ModuleUtil.findModuleForFile(psiFile);
        this.anActionEvent=anActionEvent;
//        //光标下的元素
//        PsiFile xmlFile = getSelectedElement();
//        if (xmlFile == null) {
//            return;
//        }
        //遍历文件元素,找到有id的组件
//        resIdBeanList.clear();
//        getResIdBean(xmlFile, resIdBeanList);

//        if (resIdBeanList.size() == 0) {
//            ToastUtils.toastShort(editor, "没有带id的组件:");
//            return;
//        }

        System.out.println("project:"+project.getName());
        System.out.println("psiFile:"+psiFile.getName());

        classWriter = new ClassWriter(project, psiFile, mConstFields);

        if (jsonDialog == null) {
            jsonDialog = new JsonDialog();
        }
        jsonDialog.setOnListener(onJsonDialogListener);
        jsonDialog.pack();
        jsonDialog.setLocationRelativeTo(WindowManager.getInstance().getFrame(anActionEvent.getProject()));
        jsonDialog.setVisible(true);



//        fieldTableDialog.setTitle("FindViewById");
//        fieldTableDialog.pack();
//        fieldTableDialog.setLocationRelativeTo(WindowManager.getInstance().getFrame(anActionEvent.getProject()));
//        fieldTableDialog.setVisible(true);


    }




    /**
     * 根据文件名查找文件
     *
     * @param xmlFileName
     * @return
     */
    private PsiFile getFileByName(String xmlFileName) {
        //获取文件
        PsiFile[] filesByName = FilenameIndex.getFilesByName(project, xmlFileName, GlobalSearchScope.moduleScope(module));
        String msg = "文件名:" + xmlFileName;
        msg += "---module:" + (module != null ? module.getName() : "module==null");
        msg += "---文件:" + (filesByName.length > 0 ? filesByName[0] : "filesByName.length=0");
        System.out.println(msg);
//        showDialog(editor,msg,3);
        if (filesByName.length == 0) {
            return null;
        }
        return filesByName[0];
    }

    /**
     * 获取光标选中的文件
     *
     * @return
     */
    private PsiFile getSelectedElement() {
        PsiFile xmlFile = null;
        if (editor != null) {
            //得到编辑器的光标类
            CaretModel caretModel = editor.getCaretModel();
            //程序结构接口
            //光标开始位置
            int offset = caretModel.getOffset();
            if (psiFile != null) {
                //光标下面的元素(单词)
                for (int i = -1; i <= 1; i++) {
                    PsiElement element = psiFile.findElementAt(offset + i);
                    if (element != null) {
                        String text = element.getText().trim();
                        //文件名,记住要拼接上后缀
                        String xMlFileName = String.format("%s.xml", text);
                        xmlFile = getFileByName(xMlFileName);
                    }
                    if (xmlFile != null) {
                        return xmlFile;
                    }
                }
            }
        }
        ToastUtils.toastShort(editor, "没有找到文件");
        return xmlFile;
    }

    /**
     * 获取光标下面的元素
     *
     * @return
     */
    private PsiElement getPsiElement() {
        PsiElement psiElement = null;
        if (editor != null) {
            //得到编辑器的光标类
            CaretModel caretModel = editor.getCaretModel();
            //程序结构接口
            //光标开始位置
            int offset = caretModel.getOffset();
            if (psiFile != null) {
                //光标下面的元素(单词)
                PsiElement element = psiFile.findElementAt(offset);
                PsiElement element1 = psiFile.findElementAt(offset - 1);
                //注意光标在R.layout.activity_main的后面时选择的是")" 所以需要判断
                String text = element.getText().trim();
                String text1 = element1.getText();
                //文件名

                if (!".".equals(text) && !")".equals(text) && !",".equals(text) && !"".equals(text) && !";".equals(text)) {
                    psiElement = element;
                } else {
                    psiElement = element1;

                }
            }
        }
        return psiElement;
    }

    private JsonDialog.OnListener onJsonDialogListener = new JsonDialog.OnListener() {
        @Override
        public void onOk(List<ConstField> fields) {
            if(fields!=null && fields.size()>0){
                mConstFields.clear();
                mConstFields.addAll(fields);
                if (fieldTableDialog == null) {
                    fieldTableDialog = new FieldTableDialog();
                }
                fieldTableDialog.setOnListener(onDialogListener);
                fieldTableDialog.setConstFields(mConstFields);
                fieldTableDialog.pack();
                fieldTableDialog.setLocationRelativeTo(WindowManager.getInstance().getFrame(anActionEvent.getProject()));
                fieldTableDialog.setVisible(true);
            }else {
                ToastUtils.toastLong(editor, fields != null ? fields.toString() : "fields is null");
            }



        }

        @Override
        public void onCancel() {

        }
    };


    private FieldTableDialog.OnListener onDialogListener = new FieldTableDialog.OnListener() {

        @Override
        public void onOk() {
            classWriter.generateCode();
        }

        @Override
        public void onCancel() {

        }

    };


}
